import callApp from './callApp';
window.androidCallbackBridge = null;
//判断终端类型
const u = navigator.userAgent;
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
const isIos = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

export default {
  /**
   * 关闭webview
   */
  $exitApp: function() {
    if (isAndroid) {
      SLScript.slFinish();
    } else if (isIos) {
      callApp(bridge => {
        bridge.callHandler('slFinish', {}, response => {});
      });
    }
  },

  /**
   * 分享
   * @param {String} title
   * @param {String} content
   * @param {String} url
   * @param {String} imageUrl
   */
  $shareWechat: function(title, content, url, imageUrl, platform) {
    return new Promise((resolve, reject) => {
      try {
        androidCallbackBridge = function(result) {
          console.log(result, '分享信息');
          window.resolveLoginRT(result.data);
        };
        if (window.APP_PLATFORM === 'android') {
          return SLScript.slUmShareCallback(platform, title, content, url, imageUrl);
        } else {
          window.resolveLoginRT = resolve;
          callApp(bridge => {
            bridge.callHandler(
              'slUmShareCallback',
              {
                title: title,
                content: content,
                toUrl: url,
                imgUrl: imageUrl,
                platform: platform,
              },
              androidCallbackBridge
            );
          });
        }
      } catch (error) {
        reject(error);
      }
    });
  },

  //从相册选择视频
  $ChooseVideo: function(maxNum) {
    return new Promise((resolve, reject) => {
      window.resolveLoginRT = resolve;
      try {
        window.androidCallbackBridge = function(res) {
          console.log(res, '原生返回视频');
          window.resolveLoginRT(res);
        };

        if (window.APP_PLATFORM === 'android') {
          console.log('进入安卓');
          SLScript.slChooseVideos(maxNum, window.androidCallbackBridge);
        } else {
          callApp(bridge => {
            bridge.callHandler(
              'slChooseVideos',
              {
                maxNum: maxNum,
                duration: 30000,
              },
              window.androidCallbackBridge
            );
          });
        }
      } catch (error) {
        reject(error);
      }
    });
  },
  //保存到本地

  $SaveFire: function(picUrl) {
    return new Promise((resolve, reject) => {
      try {
        window.androidCallbackBridge = function(result) {
          console.log(result, '原生返回');
          window.resolveLoginRT = result;
          let resData;
          if (typeof result == 'string') {
            resData = JSON.parse(result);
            console.log(88888888);
            resolve(JSON.parse(result));
          } else {
            resData = result;
            if (window.APP_PLATFORM !== 'android') {
              resolve(result);
            }
          }
          if (resData.status) {
            this.$loading.hide();
          }
          // resolve(JSON.parse(result.data));
        };

        if (window.APP_PLATFORM === 'android') {
          console.log(222);
          console.log(SLScript.slSavePhotoCallback(picUrl, androidCallbackBridge));
        } else {
          window.resolveLoginRT = resolve;
          callApp(bridge => {
            bridge.callHandler(
              'slSavePhotoCallback',
              {
                picUrl: picUrl,
              },
              androidCallbackBridge
            );
          });
        }
      } catch (error) {
        reject(error, 'fffffdgdgdgd');
      }
    });
  },

  /**
   * 根据业务参数获取用户信息
   * @param {String} destination 目标点
   */
  $getUserInfo() {
    return new Promise(function(resolve, reject) {
      // const deviceType = store.state.modulesCommon.device_info.deviceType;
      try {
        if (window.APP_PLATFORM === 'android') {
          if (window.WebViewJavascriptBridge) {
            window.WebViewJavascriptBridge.callHandler(
              'getUserInfoCallback',
              {
                businessClass: 'XSC',
              },
              function(res) {
                console.log(typeof res);
                if (typeof res == 'string') {
                  resolve(JSON.parse(res));
                } else {
                  resolve(res);
                }
              }
            );
          } else {
            document.addEventListener(
              'WebViewJavascriptBridgeReady',
              function() {
                console.log('WebViewJavascriptBridge---->', WebViewJavascriptBridge);
                window.WebViewJavascriptBridge.callHandler(
                  'getUserInfoCallback',
                  {
                    businessClass: 'XSC',
                  },
                  function(res) {
                    console.log(typeof res);

                    if (typeof res == 'string') {
                      resolve(JSON.parse(res));
                    } else {
                      resolve(res);
                    }
                  }
                );
              },
              false
            );
          }
        } else if (window.APP_PLATFORM == 'ios') {
          callApp(function(bridge) {
            bridge.callHandler(
              'getUserInfoCallback',
              {
                businessClass: 'XSC',
              },
              function(response) {
                console.log(response);
                resolve(response);
              }
            );
          });
        }
      } catch (e) {
        reject(e);
      }
    });
  },

  /**
   * 根据业务参数获取token
   * @param {String} destination 目标点
   */
  $getToken() {
    return new Promise(function(resolve, reject) {
      // const deviceType = store.state.modulesCommon.device_info.deviceType;
      if (window.APP_PLATFORM === 'android') {
        if (window.WebViewJavascriptBridge) {
          window.WebViewJavascriptBridge.callHandler(
            'getUserTokenCallback',
            {
              businessClass: 'XSC',
            },
            function(res) {
              console.log(typeof res);
              if (typeof res == 'string') {
                resolve(JSON.parse(res));
              } else {
                resolve(res);
              }
            }
          );
        } else {
          document.addEventListener(
            'WebViewJavascriptBridgeReady',
            function() {
              window.WebViewJavascriptBridge.callHandler(
                'getUserTokenCallback',
                {
                  businessClass: 'XSC',
                },
                function(res) {
                  console.log(typeof res);

                  if (typeof res == 'string') {
                    resolve(JSON.parse(res));
                  } else {
                    resolve(res);
                  }
                }
              );
            },
            false
          );
        }
      } else if (window.APP_PLATFORM === 'ios') {
        callApp(function(bridge) {
          bridge.callHandler(
            'getUserTokenCallback',
            {
              businessClass: 'XSC',
            },
            function(response) {
              resolve(response);
            }
          );
        });
      }
    });
  },

  //H5返回上一页
  $toGoBack() {
    console.log('return');
    return new Promise(function(resolve, reject) {
      // const deviceType = store.state.modulesCommon.device_info.deviceType;
      if (window.APP_PLATFORM === 'android') {
        if (window.WebViewJavascriptBridge) {
          window.WebViewJavascriptBridge.callHandler('platformBack', {}, function(res) {
            console.log(typeof res);
            if (typeof res == 'string') {
              resolve(JSON.parse(res));
            } else {
              resolve(res);
            }
          });
        } else {
          document.addEventListener(
            'WebViewJavascriptBridgeReady',
            function() {
              window.WebViewJavascriptBridge.callHandler('platformBack', {}, function(res) {
                console.log(typeof res);

                if (typeof res == 'string') {
                  resolve(JSON.parse(res));
                } else {
                  resolve(res);
                }
              });
            },
            false
          );
        }
      } else if (window.APP_PLATFORM == 'ios') {
        callApp(function(bridge) {
          bridge.callHandler('platformBack', {}, function(response) {
            resolve(response);
          });
        });
      }
    });
  },

  //下载文件
  $DownLoadFire(fileUrl) {
    return new Promise(function(resolve, reject) {
      // const deviceType = store.state.modulesCommon.device_info.deviceType;
      if (window.APP_PLATFORM === 'android') {
        if (window.WebViewJavascriptBridge) {
          console.log('ddddddd');
          window.WebViewJavascriptBridge.callHandler(
            'platformDownloadFile',
            {
              fileUrl: fileUrl,
            },
            function(res) {
              resolve(res);
            }
          );
        } else {
          document.addEventListener(
            'WebViewJavascriptBridgeReady',
            function() {
              console.log('WebViewJavascriptBridge---->', WebViewJavascriptBridge);
              window.WebViewJavascriptBridge.callHandler(
                'platformDownloadFile',
                {
                  fileUrl: fileUrl,
                },
                function(res) {
                  resolve(res);
                }
              );
            },
            false
          );
        }
      } else if (window.APP_PLATFORM == 'ios') {
        callApp(function(bridge) {
          bridge.callHandler(
            'platformDownloadFile',
            {
              fileUrl: fileUrl,
            },
            function(response) {
              resolve(response);
            }
          );
        });
      }
    });
  },
  //返回视频路径
  $ReturnPath(path, token) {
    return new Promise(function(resolve, reject) {
      if (window.APP_PLATFORM === 'android') {
        if (window.WebViewJavascriptBridge) {
          console.log('dd');
          window.WebViewJavascriptBridge.callHandler(
            'getFileUrlByPath',
            {
              path: path,
              token: token,
              maxDuration: 30000,
            },
            function(res) {
              console.log(res, 444);
              resolve(res);
            }
          );
        } else {
          document.addEventListener(
            'WebViewJavascriptBridgeReady',
            function() {
              console.log('WebViewJavascriptBridge---->', WebViewJavascriptBridge);
              window.WebViewJavascriptBridge.callHandler(
                'getFileUrlByPath',
                {
                  path: path,
                  token: token,
                },
                function(res) {
                  resolve(res);
                }
              );
            },
            false
          );
        }
      } else if (window.APP_PLATFORM == 'ios') {
        callApp(function(bridge) {
          bridge.callHandler(
            'getFileUrlByPath',
            {
              path: path,
              token: token,
              maxDuration: '30000',
            },
            function(response) {
              resolve(response);
            }
          );
        });
      }
    });
  },

  // 上传图片
  $ChoosePicture: function(maxNum) {
    return new Promise(function(resolve, reject) {
      if (!isIphone()) {
        console.log(818);
        window.resolved = resolve;
        androidCallbackBridge = result => {
          try {
            window.resolved(result);
          } catch (e) {
            console.log(e);
          }
        };
        SLScript.slSelectPhotosFromAlbumCallback(maxNum, androidCallbackBridge);
      } else {
        callApp(function(bridge) {
          bridge.callHandler('slSelectPhotosFromAlbumCallback', { num: `${maxNum}` }, function(
            response
          ) {
            resolve(response);
          });
        });
      }
    });
  },
  // 获取通讯录
  $getContacts: function() {
    return new Promise(function(resolve, reject) {
      if (!isIphone()) {
        console.log(818);
        window.resolved = resolve;
        androidCallbackBridge = result => {
          try {
            window.resolved(result);
          } catch (e) {
            console.log(e);
          }
        };
        SLScript.slGetContactsCallback(androidCallbackBridge);
      } else {
        callApp(function(bridge) {
          bridge.callHandler('slGetContactsCallback', {}, function(response) {
            resolve(response);
          });
        });
      }
    });
  },
  $jumpWXMiniProgress() {
    console.log('---jumpWXMiniProgress-------');
    return new Promise(function(resolve, reject) {
      // const deviceType = store.state.modulesCommon.device_info.deviceType;
      window.WebViewJavascriptBridge.callHandler(
        'getWXMiniProgress',
        { path: '', wxMiniId: 'gh_2793a8e526ea' },
        function(res) {
          resolve(res);
        }
      );
    });
  },
  $jumpSecondPage(routePath, packageName) {
    return new Promise(function(resolve, reject) {
      window.WebViewJavascriptBridge.callHandler(
        'openWebWindowCallback',
        {
          title: '',
          url: '', // 跳转的地址 0:H5外链必传
          style: '0', // 0= 隐藏导航栏； 1=显示返回按钮（逐级返回）+X（关闭按钮）；2=显示返回按钮（逐级返回），隐藏X（关闭按钮）；3=隐藏返回按钮，显示X（关闭按钮）
          loadType: '1', //loadType: 0:H5外链， 1：本地加载。 默认0
          packageName: packageName || 'com.bonade.h5.xxf.welfare', // 包名 1：本地加载。必传
          route: routePath, // 路由 1：本地加载。必传:#/me.必须带井号
        },
        function(res) {
          resolve(res);
        }
      );
    });
  },
  $OnscrollTo(value) {
    console.log('Onscroller');
    // return new Promise(function (resolve, reject) {
    //   if (window.APP_PLATFORM == "ios") {
    //     console.log("scroller======================")
    //     callApp(function (bridge) {
    //       bridge.callHandler(
    //         "scrollToValue",
    //         {
    //           value: value
    //         },
    //         function (response) {
    //           resolve(response);
    //         }
    //       );
    //     });
    //   }
    // })
    return new Promise(function(resolve, reject) {
      console.log('进入方法');
      window.WebViewJavascriptBridge.callHandler('scrollToValue', { value: value }, function(res) {
        resolve(res);
      });
    });
  },
  $returnFresh() {
    console.log('---returnFresh-------');
    return new Promise(function(resolve, reject) {
      // const deviceType = store.state.modulesCommon.device_info.deviceType;
      window.WebViewJavascriptBridge.callHandler(
        'refreshRelatives',
        { hpage: 'familyCare' },
        function(res) {
          resolve(res);
        }
      );
    });
  },
};
/** 判断系统 */
export function isIphone() {
  const ua = window.navigator.userAgent.toLowerCase();
  if (ua.indexOf('android') !== -1) {
    return false; // android
  } else {
    return true; // ios
  }
}
